﻿using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace Sidvall.WorkItemManager.Web.Controllers.Api.V1
{
    public class WorkItemManagerServerContentController : ApiController
    {
        #region GetItem

        [HttpGet]
        [Route("api/V1/WorkItemManagerServerContent/GetItem")]
        public async Task<HttpResponseMessage> GetItem()
        {
            HttpResponseMessage message;

            var dataPortalContext = Sidvall.Business.DataPortalManager.NewContext("WorkItemManagerServerContent", Sidvall.Security.Operations.GetItems, null, true);
            try
            {
                await Sidvall.WorkItemManager.Web.SystemContext.Current.ControllerManager.EnsureIsAuthorizedAsync(this, dataPortalContext);

                var serverContent = await Sidvall.Security.SecurityManager.GetServerContentAsync(Sidvall.SystemContext.Current.PrincipalManager.CurrentPrincipal.Identity,
                    Sidvall.WorkItemManager.Security.SecurityManager.AuthorityUserInfoEndpoint, this.Request.Headers.Authorization.Parameter, true, false, true, null);
                message = this.Request.CreateResponse(HttpStatusCode.OK, serverContent);
            }
            catch (System.Exception ex)
            {
                await Sidvall.WorkItemManager.Web.SystemContext.Current.ControllerManager.LogAsync(ex);
                message = Sidvall.WorkItemManager.Web.SystemContext.Current.ControllerManager.GetResponseMessage(this, ex);
                dataPortalContext.Exception = ex;
                global::Sidvall.WorkItemManager.Web.Controllers.Api.V1.ControllerEventManager.DataPortalException(dataPortalContext);
                await dataPortalContext.DoTaskAsync(false);
            }
            return message;
        }

        #endregion
    }
}